<?php

namespace App\Controller\AdminApi;

use App\Base\IRI;
use App\Base\BaseForm;
use App\Base\ActionBox\ActionBox;
use App\Base\SearchBox\SearchBox;
use App\Base\BaseController4Admin;
use App\Entity\MoneyLogType;
use App\Entity\MoneyType;
use App\Repository\MoneyLogTypeRepository;
use App\Repository\MoneyTypeRepository;
use App\Service\MoneyService;
use Symfony\Component\Routing\Annotation\Route;

use App\Repository\MoneyRepository as Repository;
use App\Entity\Money as Entity;

/**
 * @Route("/admin/")
 */
class MoneyAdminApiController extends BaseController4Admin
{
    public $noDelete = [];
    public $entityName = "Money";
    public $limit = 10;

    /**
     * @Route("Money/form",name="MoneyForm")
     */
    public function form(
        Repository $repository,
        MoneyTypeRepository $moneyTypeRepository,
        MoneyLogTypeRepository $moneyLogTypeRepository
    )
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]??0);
        $next = 0;
        $prev = 0;
        if (!$entity) {
            $entity = new Entity();
        }else{
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["gt"=>["id"=>$data["id"]??0]]);
            $qb->setFirstResult(0)->setMaxResults(1);
            $qb->orderBy("A.id","ASC");
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $next = $rst[0]->getId();
                }
            }
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["lt"=>["id"=>$data["id"]??0]]);
            $qb->orderBy("A.id","DESC");
            $qb->setFirstResult(0)->setMaxResults(1);
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $prev = $rst[0]->getId();
                }
            }
        }
        $BaseForm = new BaseForm(Entity::class);
        //表单选项

        $BaseForm->addRadio("type","资金账户",$moneyTypeRepository->get4Choice())->ruleNotNull()->getData();
        $BaseForm->addSelect("log","变动类型",$moneyLogTypeRepository->get4ChoiceWithCode())->ruleNotNull()->getData();
        $BaseForm->addText("money","变动数量")->getData();
        $BaseForm->addText("tips","备注说明")->getData();

        $entity = $this->toArray($entity);
        $BaseForm->setEntity($entity);
        $data = array(
            "title" => "创建表单",
            "show"   => $BaseForm->createForm(),
            "isAdd"   => true,
            "next"   => $next,
            "prev"   => $prev,
        );
        return $this->json_out(1,"OK",$data);
    }

    /**
     * @Route("Money/submit",name="MoneySubmit",methods={"POST"})
     */
    public function submit(
        Repository $repository
        ,MoneyService $moneyService
    )
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]?:0);
//        if (!$entity) {$entity = new  Entity();}
//        /**@var $Money Entity*/
//        $Money = $this->updateEntity($data,Entity::class,$entity);
//        $this->myEm()->persist($Money);$this->myEm()->flush();
//        return $this->json_out(1,"保存成功","/admin/list/auto?en=".$this->entityName);
        if (!$entity) {
            $this->json_out(0,"请勿直接增加用户资产数据");
        }else{
            $user = $entity->getUser();
            $moneyType = $data["type"]??$entity->getType();
            $logType = $data["log"]??"";
            $money = $data["money"]??"";
            if ($logType >=200 && $logType < 300) {
                $money *= -1;
            }
            $moneyService->mod($user,$money,$moneyType,$logType,$data["tips"]??"");
            return $this->json_out(1,"保存成功","/admin/list/auto?en=".$this->entityName);
        }
    }

    /**
     * @Route("Money/list",name="MoneyGetList")
     */
    public function getList(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $per_page   = $this->limit;
        $page       = $data["page"]??1;
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];

        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,["user.name","user.phone"],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
//        $list= $this->normalize($list);
        foreach ($list as &$row) {

            $phone = $row->getUser()->getPhone()?:'未设置手机号';
            /**@var $row Entity*/
            $row = [
                "id"=>$row->getId(),
                "user"=>$row->getUser()->getName()."[ $phone ]",
                "type"=>$row->getType()->getName(),
                "money"=>$row->getMoney(),
            ];
        }

        //列表计数
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,["user.name","user.phone"],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        //表头数据和列表内展示形式
        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);

        //设置筛选数据表单
        $sb = new SearchBox();
        $sb->setExcel(false);
        //todo 设置筛选数据
        $sb->addText("user.phone")->setHelpText("用户手机号")->createData();
        $sb->addText("user.name")->setHelpText("用户昵称")->createData();
        //设置筛选数据表单
        $ab = new ActionBox();
        //todo 设置筛选数据
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => ["id","money","type","user"],
            "config"    => $config,
            'lists'     => $list,
            'searchBox' => $sb->createData(),
            'actionBox' => $ab->createData(),
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }

    /**
     * @Route("Money/excel",name="MoneyGetListExcel")
     */
    public function getListExcel(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];
        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);
        $title=[
            "","","","","","","","","","","","","","","","","","",""
        ];
        $this->excelOut($title,$list,"123.xls");
    }


    /**
     * @Route("Money/delete",name="MoneyDelete",methods={"POST"})
     */
    public function delete(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        foreach ($ids as $id) {
            if (in_array($id , $this->noDelete) || in_array(0 , $this->noDelete)) {continue;}
            if ($entity= $repository->find($id)) {$this->myEm()->remove($entity);}
        }
        $this->myEm()->flush();
        return $this->json_out(1,'删除成功');
    }


    /**
     * @Route("Money/action",name="MoneyAction",methods={"GET","POST"})
     */
    public function UserAction(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        $action = $this->getRequestData()["_action"]??[];
        //移除没有值的项
        foreach ($action as $key=>$value) {
            if ($value === "") {
                unset($action[$key]);
            }
        }
        foreach ($ids as $id) {
            if ($entity= $repository->find($id)) {
                $entity = $this->updateEntity($action,Entity::class,$entity);
                $this->myEm()->persist($entity);
            }
        }
        $this->myEm()->flush();
        return $this->json_out(1,'修改成功');
    }

    /**
     * @Route("Money/copy",name="MoneyCopy")
     */
    public function doCopy(Repository $repository)
    {
        $data = $this->getRequestData();
        if (!$entity = $repository->find($data["id"]??0)) {
            return $this->json_out(0,"数据丢失");
        }
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = $this->serializer->denormalize($tmp,Entity::class);
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->json_out(1,"复制成功");
    }


    /**
     * 用于entity组件窗口选择器
     * @Route("Money/search",name="MoneyGetList4EntitySelect")
     */
    public function getList4EntitySelect(Repository $repository)
    {
        $this->needToBeAdmin();
        $data = $this->getRequestData();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $where = $data['_where']??[];
        $search = $data['_search']??[];
        $order = $data["_order"]??[];

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => ["id"],
            "config"    => $config,
            'lists'     => $list,
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * 用于ENTITY组件选项关展示
     * @Route("Money/viewer",name="MoneyList4EntityViewer")
     */
    public function MoneyList4EntityViewer(Repository $repository)
    {
        $data = $this->getRequestData();
        $id = $data["id"]??0;
        if (!is_array($id)) {
            $id = [$id];
        }
        $re = [];
        foreach ($id as $v) {
            //分别分成iri 和 id 两种方式
            $arr = myExplodeNumbers($v);
            $realId = array_pop($arr);
            $en = $repository->find($realId);
            if (!$en) {continue;}
            $re[] = [
                "id" => $en->getId(),
                "val" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }

    /**
     * 用于列表组件List
     * @Route("Money/choice",name="MoneyList4ListChoice")
     */
    public function MoneyList4ListChoice(Repository $repository)
    {
        $all = $repository->findBy(array());
        foreach ($all as $en) {
            $re[] = [
                "id" => IRI::createIRIStringFromEntity(Entity::class,$en->getId()),
                "value" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }
}
